﻿@layout NewsletterLayout
@page "/admin/newsletter/subscribers/"
@inject HttpClient _http
@inject IStringLocalizer<Resource> _localizer

<PageTitle Title="@_localizer["subscribers"]" />

<h1 class="section-title">@_localizer["subscribers"]</h1>
<div class="section-content">

    @if (Subscribers == null || Subscribers.Count == 0)
    {
        <p class="list-notfound">@_localizer["not-found"]</p>
    }
    else
    {
        <ul class="list">
            @foreach (var subscriber in Subscribers)
            {
                <li class="list-item">
                    @{
                        string title = $"{subscriber.Email} / {subscriber.Country} / {subscriber.Region} / {subscriber.Ip}";
                        string pubDate = subscriber.DateCreated.ToFriendlyDateTimeString();
                    }
                    <span class="list-title">@title</span>
                    <span class="list-text">@pubDate</span>
                    <button class="list-btn" @onclick="(async () => await RemoveSubscription(subscriber.Id))" data-bs-toggle="tooltip" title="@_localizer["remove"]">
                        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="currentColor" class="bi bi-x text-danger" viewBox="0 0 16 16">
                            <path d="M4.646 4.646a.5.5 0 0 1 .708 0L8 7.293l2.646-2.647a.5.5 0 0 1 .708.708L8.707 8l2.647 2.646a.5.5 0 0 1-.708.708L8 8.707l-2.646 2.647a.5.5 0 0 1-.708-.708L7.293 8 4.646 5.354a.5.5 0 0 1 0-.708z"/>
                        </svg>
                    </button>
                </li>
            }
        </ul>
    }
</div>
<ToasterComponent @ref="Toaster" />

@code {
    protected ToasterComponent Toaster;
    protected List<Subscriber> Subscribers;

    protected override async Task OnInitializedAsync()
    {
        await Load();
    }

    protected async Task Load()
    {
        Subscribers = await _http.GetFromJsonAsync<List<Subscriber>>($"api/newsletter/subscribers");
    }

    protected async Task RemoveSubscription(int id)
    {
        Toaster.Toast(await _http.DeleteAsync($"api/newsletter/unsubscribe/{id}"));
        await Load();
    }
}
